//
//  SingleKindViewController.m
//  EarnBao
//
//  Created by xiaohui on 15/4/20.
//  Copyright (c) 2015年 杭州赚宝科技有限公司. All rights reserved.
//

#import "SingleKindViewController.h"
#import "SingleKindCollectionViewCell.h"
#import "DetailViewController.h"
#import "SingleKind.h"
#import "EarnBao-API.h"
#import "Reachability.h"
#import "MBProgressHUD.h"
#import "MJRefresh.h"
#import "DownLoadData.h"

@interface SingleKindViewController ()<DownLoadDataDelegate>
{
    int pageNumber;  //页码
}
@property (nonatomic, retain) UICollectionView *collectionView;
@property (nonatomic, retain) Reachability *whole_conn;
@property (nonatomic, retain) MBProgressHUD *hud;
@property (nonatomic ,retain) NSMutableArray *waterfallArray;

@end

@implementation SingleKindViewController

//销毁通知
- (void)dealloc
{
    [self.whole_conn stopNotifier];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

//构建子视图
-(void)setSubviews
{
    //瀑布流主体
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.itemSize = CGSizeMake(self.view.bounds.size.width*11/24, self.view.bounds.size.width*11/18);
    flowLayout.sectionInset = UIEdgeInsetsMake(self.view.bounds.size.width/48, self.view.bounds.size.width/48, self.view.bounds.size.width/48, self.view.bounds.size.width/48);
    
    self.collectionView = [[UICollectionView alloc] initWithFrame:[[UIScreen mainScreen] bounds] collectionViewLayout:flowLayout];
    _collectionView.delegate = self;  //设置代理
    _collectionView.dataSource = self;  //设置数据源
    _collectionView.showsVerticalScrollIndicator = NO;
    _collectionView.backgroundColor = [UIColor colorWithRed:240/255.0 green:240/255.0 blue:240/255.0 alpha:1.0];
    [self.view addSubview:_collectionView];
}

//数据加载完成之前显示的菊花圈
- (void)setProgressHud
{
    self.hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [_hud show:YES];
}

//视图加载完成
- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.navigationItem.title = self.titleString;
    
    UIButton *leftBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 40,35)];
    [leftBtn setContentHorizontalAlignment:UIControlContentHorizontalAlignmentRight];
    [leftBtn setImage:[UIImage imageNamed:@"nav_return"] forState:UIControlStateNormal];
    [leftBtn addTarget:self action:@selector(backToHeadPage) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftBtn];

    
    //调用构建子视图的方法
    [self setSubviews];
    
    
    //注册一个通知用来实时监测网络状态的改变
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkStateChange) name:kReachabilityChangedNotification object:nil];
    //创建一个全局的网络对象
    self.whole_conn = [Reachability reachabilityForInternetConnection];
    //开启通知
    [self.whole_conn startNotifier];
    
    //调用网络状态改变的方法
    [self networkStateChange];
    
    
    self.waterfallArray = [[NSMutableArray alloc] initWithCapacity:0];  //初始化对象数组
    pageNumber = 2;  //初始值设置为2
    [self loadData];  //视图加载完成就请求数据为了做缓存
}

#pragma mark ---实时监测网络状态的改变(一切数据请求和数据显示的相关处理均以网络状态的不同为基准进行！)---

//网络状态改变
- (void)networkStateChange
{
    [self checkNetworkState];
}

//检查网络状态
- (void)checkNetworkState
{
    //1.创建wifi网络对象
    Reachability *wifi = [Reachability reachabilityForLocalWiFi];
    
    //2.创建手机网络对象(2G/3G/4G，也就是平时常说的手机流量)
    Reachability *conn = [Reachability reachabilityForInternetConnection];
    
    //3.判断当前app的网络连接状态，通常分为以下三种情况：
    
    //有wifi连接(包括两种情况：1.只有wifi  2.手机网络和wifi同时存在，此时wifi会自动替换掉手机网络)
    if ([wifi currentReachabilityStatus] != NotReachable) {
        
        [self setProgressHud];
        [self addHeader];
        [self addFooter];
        [_hud hide:YES];
    }
    
    //只有手机网络
    if ([conn currentReachabilityStatus] != NotReachable && [wifi currentReachabilityStatus] == NotReachable) {
        
        [self setProgressHud];
        [self addHeader];
        [self addFooter];
        [_hud hide:YES];
    }
}

//用代理实现刷新
- (void)refresh
{
    [self.collectionView reloadData];
}

//加载数据
- (void)loadData
{
    DownLoadData *handle = [DownLoadData shareDataHandle];
    handle.delegate = self;
    [handle downLoadDataWithURL:self.urlString key:@"products" model:@"SingleKind" results:self.waterfallArray];
}

//加载更多数据
- (void)loadMoreData
{
    NSString *pageNumberString=[NSString stringWithFormat:@"&page=%d",pageNumber];
    NSString *urlString = [self.urlString stringByAppendingString:pageNumberString];
    
    DownLoadData *handle = [DownLoadData shareDataHandle];
    handle.delegate = self;
    [handle downLoadDataWithURL:urlString key:@"products" model:@"SingleKind" results:self.waterfallArray];
    
    //加载更多数据执行一次后页码累加1
    pageNumber ++;
}

#pragma mark ---下拉刷新，上拉加载---

//添加页头下拉刷新控件
- (void)addHeader
{
    __unsafe_unretained typeof(self) vc = self;
    
    //进入刷新状态就会回调这个Block
    [self.collectionView addHeaderWithCallback:^{
        
        [vc.collectionView reloadData];  //刷新数据
        
        //模拟延迟刷新数据，2秒后才调用，也就是转圈的动作持续2秒！
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            [vc.collectionView headerEndRefreshing];  //结束刷新动作
        });
    }];
}

//添加页脚上拉加载控件
- (void)addFooter
{
    __unsafe_unretained typeof(self) vc = self;
    
    //进入加载状态就会回调这个Block
    [self.collectionView addFooterWithCallback:^{
        
        [self loadMoreData];  //加载更多数据
        
        //模拟延迟加载数据，2秒后才调用，也就是转圈的动作持续2秒！
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            [self.collectionView footerEndRefreshing];  //结束刷新动作
        });
    }];
}

#pragma mark --- collectionView的代理方法 ---

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return [self.waterfallArray count];
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"cell";
    [collectionView registerClass:[SingleKindCollectionViewCell class] forCellWithReuseIdentifier:cellIdentifier];
    SingleKindCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];
    SingleKind *singleKind = self.waterfallArray[indexPath.row];
    cell.singleKind = singleKind;
    
    //显示包邮与否
    if ([singleKind.free_post isEqualToString:@"1"]) {
        cell.free_post_nameLabel.text = [NSString stringWithFormat:@"[包邮]%@",singleKind.name];
    }
    
    //显示天猫与否
    if ([singleKind.shop_type isEqualToString:@"B"]) {
        cell.shop_typeImageView.image = [UIImage imageNamed:@"tmall.png"];
    }
    
    //给“市场价格”添加删除线并设置样式
    NSMutableAttributedString *attri = [[NSMutableAttributedString alloc] initWithString:cell.market_priceLabel.text];
    NSUInteger length = [cell.market_priceLabel.text length];
    [attri addAttribute:NSStrikethroughStyleAttributeName value:@(NSUnderlinePatternSolid | NSUnderlineStyleSingle) range:NSMakeRange(0, length)];
    [attri addAttribute:NSStrikethroughColorAttributeName value:[UIColor blackColor] range:NSMakeRange(0, length)];
    [cell.market_priceLabel setAttributedText:attri];
    
    [_hud hide:YES];  //数据加载完成将菊花圈隐藏
    
    return cell;
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    DetailViewController *detailVC = [[DetailViewController alloc] init];
    //做一个导航控制器以实现正常跳转和返回
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:detailVC];
    SingleKind *singleKind = self.waterfallArray[indexPath.row];
    detailVC.urlString = singleKind.url;
    [self presentViewController:nav animated:YES completion:nil];
}

//当系统报内存警告时，需要手动进行处理！
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    
    // Add code to clean up any of your own resources that are no longer necessary.
    
    // 此处做兼容处理需要加上ios6.0的宏开关，保证是在6.0下使用的,6.0以前屏蔽以下代码，否则会在下面使用self.view时自动加载viewDidUnLoad
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 6.0) {
        //需要注意的是self.isViewLoaded是必不可少的，其他方式访问视图会导致它加载 ，在WWDC视频也忽视这一点。
        if (self.isViewLoaded && !self.view.window)// 是否是正在使用的视图
        {
            // Add code to preserve data stored in the views that might be
            // needed later.
            
            // Add code to clean up other strong references to the view in
            // the view hierarchy.
            self.view = nil;// 目的是再次进入时能够重新加载调用viewDidLoad函数。
        }
    }
    //self.nine_nineArray = nil;
}
//返回首页
- (void)backToHeadPage
{
    [self.navigationController popToRootViewControllerAnimated:YES];
}

@end
